package com.nondo.dean.order.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nondo.dean.auth.common.TokenPrincipalProvider;
import com.nondo.dean.common.tool.AliyunOssTool;
import com.nondo.dean.common.tool.BeanUtils;
import com.nondo.dean.common.tool.DateProcessUtils;
import com.nondo.dean.common.tool.StringUtils;
import com.nondo.dean.common.web.View;
import com.nondo.dean.order.common.Constant;
import com.nondo.dean.order.common.OrderTip;
import com.nondo.dean.order.domain.Bank;
import com.nondo.dean.order.domain.TransferDetail;
import com.nondo.dean.order.domain.TransferDetailExample;
import com.nondo.dean.order.mapper.TransferDetailExtendsMapper;
import com.nondo.dean.order.mapper.TransferDetailMapper;
import com.nondo.dean.order.model.*;

import com.nondo.dean.order.model.param.TransferDetailParam;
import com.nondo.dean.order.model.result.TransferDetailResult;
import org.apache.commons.collections.map.HashedMap;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @author xiaofan
 * @Description: 经销商打款业务处理类
 * @throws
 * @date 2018-06-1514:23
 * @Version
 */
@Component
public class TransferDetailService {
    @Autowired
    private TransferDetailMapper transferDetailMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private BankService bankService;

    @Autowired
    private TransferDetailExtendsMapper transferDetailExtendsMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    TokenPrincipalProvider tokenPrincipalProvider;

    @Autowired
    AliyunOssTool aliyunOssTool;

    /**
     * 新增
     * @param transferDetailModelBean
     * @return
     */
    public int add(TransferDetailModelBean transferDetailModelBean){
        TransferDetail transferDetail = new TransferDetail();
        BeanUtils.copy(transferDetailModelBean,transferDetail);
        transferDetail.setTransactionImage(this.imageSplit(transferDetailModelBean.getImageList()));
        transferDetail.setStatus(1);
        return transferDetailMapper.insertSelective(transferDetail);
    }

    /**
     * 修改
     * @param transferDetailModelBean
     * @return
     */
    @Transactional
    public int update(TransferDetailModelBean transferDetailModelBean){
        TransferDetail transferDetail = new TransferDetail();
        BeanUtils.copy(transferDetailModelBean,transferDetail);
        transferDetail.setTransactionImage(this.imageSplit(transferDetailModelBean.getImageList()));
        return transferDetailMapper.updateByPrimaryKeySelective(transferDetail);
    }


    /**
     * 删除
     * @param transferDetail
     * @return
     */
    public int delete(TransferDetail transferDetail){
        transferDetail.setDelFlag(TransferDetail.DEL_FLAG_DELETE);
        return  transferDetailMapper.updateByPrimaryKeySelective(transferDetail);
    }

    /**
     * 按id查询
     * @param id
     * @return
     */
    public TransferDetail select(Integer id){
        return  transferDetailMapper.selectByPrimaryKey(id);
    }



    /**
     * 查询条件
     * @param criteria
     * @param transferDetail
     */
    void setCriteria(TransferDetailExample.Criteria criteria, TransferDetail transferDetail) {
        if (transferDetail != null) {
            if (transferDetail.getId() != null) {
                criteria.andIdEqualTo(transferDetail.getId());
            }
            if (StringUtils.isNoneBlank(transferDetail.getBankname())) {
                criteria.andBanknameEqualTo(transferDetail.getBankname());
            }
            if (transferDetail.getMoneyUsed() != null) {
                criteria.andMoneyUsedEqualTo(transferDetail.getMoneyUsed());
            }
            if (transferDetail.getStatus() != null) {
                criteria.andStatusEqualTo(transferDetail.getStatus());
            }

        }
        criteria.andDelFlagEqualTo(TransferDetail.DEL_FLAG_NORMAL);
    }

    /**
     * 统计
     * @param transferDetail
     * @return
     */
    public Long count(TransferDetail transferDetail){
        TransferDetailExample example = new  TransferDetailExample();
        TransferDetailExample.Criteria criteria= example.createCriteria();
        setCriteria(criteria,transferDetail);
        return transferDetailMapper.countByExample(example);
    }

    /**
     * 获取列表
     * @param offset
     * @param limit
     * @param transferDetail
     * @return
     */
    public List<TransferDetail> getList(int offset, int limit, TransferDetail transferDetail){
        List<TransferDetail> newList = new ArrayList<TransferDetail>();
        RowBounds rowBounds = new RowBounds(offset,limit);
        TransferDetailExample example = new TransferDetailExample();
        example.setOrderByClause("id DESC");
        TransferDetailExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria,transferDetail);
        newList =transferDetailMapper.selectByExampleWithRowbounds(example,rowBounds);
        return newList;
    }

    /**
     * 获取经销商数据
     * @param userId
     * @return
     */
    public TransferUserBean seacherUser(Integer userId){
        TransferUserBean transferUserBean = new TransferUserBean();
        View view = restTemplate.postForEntity("http://dean-platform/platform/v1/inner/user/select/"+userId, null,
                View.class).getBody();
        if(view.getCode()==20000 && view.getData() != null){
            String str = JSON.toJSONString(view.getData());
            transferUserBean = JSONObject.parseObject(str,TransferUserBean.class);
        }
        return transferUserBean;
    }

    /**
     * 修改打款记录状态
     * @param bean
     * @return
     */
    public int updateStauts(TransferDetail bean){
        if(bean == null){
            bean = new TransferDetail();
        }
        return transferDetailMapper.updateByPrimaryKeySelective(bean);
    }

    /**
     * 查询打款详情
     * @param id
     * @return
     */
    public TransferDetailResult details(Integer id){
        TransferDetailResult resultBean = new TransferDetailResult();
        TransferDetail transferDetail= transferDetailMapper.selectByPrimaryKey(id);
        BeanUtils.copy(transferDetail,resultBean);
        resultBean.setAttachBeanList(this.compoundImagePath(transferDetail.getTransactionImage()));
        //经销商数据
        resultBean.setTransferUserBean(seacherUser(transferDetail.getUserId()));
        //银行数据
        resultBean.setBankBean(bankService.selectBank(transferDetail.getBankId()));

        return resultBean;
    }

    /**
     * 查询经销商打款记录表生成凭证
     * @param param
     * @return
     */
    public List<TransferDetailResult> searchRemit(TransferDetailParam param){
        List<TransferDetailResult> newList = new ArrayList<>();
        List<TransferDetail> transferDetailList = transferDetailExtendsMapper.selectByExample(param);
        for(TransferDetail beans : transferDetailList){
            TransferDetailResult result = new TransferDetailResult();
            result.setId(beans.getId());
            result.setDealAmount(beans.getDealAmount());
            result.setDealTime(DateProcessUtils.formatTimestampToDate(beans.getCreateDate()));
            result.setDealBankname(beans.getDealBankname());
            result.setTransactionMode(beans.getTransactionMode());
            result.setMoneyUsed(beans.getMoneyUsed());
            String mess= beans.getDealSummary();

            //经销商数据
            result.setTransferUserBean(seacherUser(beans.getUserId()));
            //银行数据
            result.setBankBean(bankService.selectBank(beans.getBankId()));

            if(StringUtils.isNotBlank(result.getTransferUserBean().getProxyCode()) && !result.getTransferUserBean().getProxyCode().equals(result.getTransferUserBean().getUserNo()) && "1".equals(result.getMoneyUsed())){
                mess+= OrderTip.REMIT_PROXY_MESSAGE;
            }
            result.setDealSummary(mess);
            newList.add(result);
        }
        return newList;
    }

    /**
     * 查询凭证打印
     * @param param
     * @return
     */
    public List<TransferDetailResult> searchProof(TransferDetailParam param){
        List<TransferDetailResult> newList = new ArrayList<>();
        List<TransferDetail> transferDetailList = transferDetailExtendsMapper.selectProof(param);
        for(TransferDetail beans : transferDetailList){
            TransferDetailResult result = new TransferDetailResult();
            result.setDealAmount(beans.getDealAmount());
            result.setDealTime(DateProcessUtils.formatTimestampToDate(beans.getCreateDate()));
            result.setAttachBeanList(compoundImagePath(beans.getTransactionImage()));
            //经销商数据
            result.setTransferUserBean(seacherUser(beans.getUserId()));
            //银行数据
            result.setBankBean(bankService.selectBank(beans.getBankId()));
            newList.add(result);
        }
        return newList;
    }

    /**
     * 处理传入的图片已字符串形式，号分割
     * @param attachBeans
     * @return
     */
    public String imageSplit(List<AttachBean> attachBeans){
        String imagePath="";
        if(attachBeans != null && !attachBeans.isEmpty()){
            for(AttachBean beans : attachBeans){
                imagePath += beans.getName()+",";
            }
            imagePath=imagePath.substring(0,imagePath.length()-1);
        }
        return  imagePath;
    }

    /**
     * 将字符串形式的图片路径处理成List集合
     * @param imagePath
     * @return
     */
    public List<AttachBean> compoundImagePath(String imagePath){
        List<AttachBean> newList = new ArrayList<>();
        String[] path = imagePath.split(",");
        int index = 1;
        for(int i= 0; i < path.length; i++){
            index ++;
            AttachBean beans = new AttachBean();
            beans.setName(path[i]);
            beans.setUrl(aliyunOssTool.getImgUrl(path[i]));
            beans.setUid(String.valueOf(index));
            newList.add(beans);
        }
        return newList;
    }

    /**
     * 查询银行和打款记录
     * @param param
     * @return
     */
    public TransferMainBean searchData(TransferMainBean param){
        TransferMainBean beans = new TransferMainBean();
        StringBuffer strErr = new StringBuffer();
        //银行信息
        Bank bank = bankService.select(param.getBankId());
        beans.setBankId(bank.getId());
        beans.setDelFlag(bank.getDelFlag());
        beans.setSapBankSubject(bank.getSapBankSubject());
        beans.setRemitTanceTime(param.getRemitTanceTime());
        beans.setIds(param.getIds());
        beans.setBankName(bank.getBankname());
        //打款记录明细
        List<TransferDetailBean> newList = new ArrayList<>();
        List<Integer> ids = Arrays.asList(param.getIds());
        TransferDetailExample example = new TransferDetailExample();
        example.createCriteria().andIdIn(ids).andDelFlagEqualTo(TransferDetail.DEL_FLAG_NORMAL);
        List<TransferDetail> list = transferDetailMapper.selectByExample(example);
        double sumAmount=0;
        for(TransferDetail newBeans : list){
            TransferDetailBean detailBean = new TransferDetailBean();
            sumAmount+=newBeans.getDealAmount().doubleValue();
            detailBean.setId(newBeans.getId());
            detailBean.setDealAmount(newBeans.getDealAmount().toPlainString());
            detailBean.setRemitTanceTime(DateProcessUtils.formatTimestampToDate(newBeans.getRemittanceTime()));
            detailBean.setDelFlag(newBeans.getDelFlag());
            detailBean.setMoneyUsed(newBeans.getMoneyUsed());
            detailBean.setSapNo(newBeans.getSapNo());
            detailBean.setStatus(newBeans.getStatus());
            detailBean.setTransactionMode(newBeans.getTransactionMode());
            //经销商数据
            TransferUserBean userBean = seacherUser(newBeans.getUserId());
            detailBean.setCrmCode(userBean.getUserNo());
            detailBean.setCrmName(userBean.getUserName());
            detailBean.setRegionName(userBean.getRegionName());
            detailBean.setProxyCode(userBean.getProxyCode());
            String str = "第'"+newBeans.getId()+"'行项目异常:";
            if(StringUtils.isNotBlank(newBeans.getSapNo())){
                strErr.append(str + OrderTip.ERR_CREATE_CREDENTIALS + newBeans.getSapNo() + OrderTip.ERR_NOT_CREATE);
            }else if(Constant.WATTING_SYNCHRONIZED.equals(newBeans.getStatus())){
                strErr.append(str + OrderTip.ERR_REPETITION_CREATE);
            }
            newList.add(detailBean);
        }
        beans.setTotalAmount(sumAmount);
        beans.setTransferDetailBeanList(newList);
        beans.setDetailError(strErr.toString());
        return beans;
    }

    /**
     * 打款记录校验
     * @param bean
     * @return
     */
    public Map<String,String> checkTransferDetail(TransferMainBean bean){
        Map<String,String> reMap= new HashMap<>();
        if(null == bean.getBankId()) {
            reMap.put(OrderTip.STRING_MESSAGE_ALERT, OrderTip.ERR_NOT_BANK);
        }else if(!StringUtils.isNotBlank(bean.getSapAccount())){
            reMap.put(OrderTip.STRING_MESSAGE_ALERT, OrderTip.ERROR_SAP_ID);
        }else if(TransferDetail.DEL_FLAG_DELETE.equals(bean.getDelFlag())){
            reMap.put(OrderTip.STRING_MESSAGE_ALERT, bean.getBankName() + OrderTip.ERR_DELETE_BANK);
        }else if(bean.getTransferDetailBeanList().size() == 0){
            reMap.put(OrderTip.STRING_MESSAGE_ALERT, OrderTip.ERR_READ_ITEM);
        }else if(!StringUtils.isNotBlank(bean.getSapBankSubject())){
            reMap.put(OrderTip.STRING_MESSAGE_ALERT, OrderTip.ERR_SAP_SUBJECT);
        }else if(StringUtils.isNotBlank(bean.getDetailError())) {
            reMap.put(OrderTip.STRING_MESSAGE_ALERT, OrderTip.ERR_ITEM_ERROR + bean.getDetailError());
        }

        return reMap;
    }

    /**
     * 修改sap返回的sap凭证编号
     * @param arrayId
     * @param sapCode
     */
    public void updateSapCode(Integer[] arrayId,String sapCode){
        List<Integer> ids = Arrays.asList(arrayId);
        TransferDetail bean = new TransferDetail();
        bean.setSapNo(sapCode);
        TransferDetailExample example = new TransferDetailExample();
        example.createCriteria().andIdIn(ids);
        transferDetailMapper.updateByExampleSelective(bean,example);
        //修改状态
        TransferDetailExample example2 = new TransferDetailExample();
        example.createCriteria().andIdIn(ids);
        TransferDetail bean2 = new TransferDetail();
        bean2.setStatus(4);
        transferDetailMapper.updateByExampleSelective(bean2,example);
    }

    /**
     * 处理打款记录传输
     * @param param
     * @return
     */
    public Map<String,String> transferPaymentRecord(TransferMainBean param){
        Map<String,String> reMap = new HashMap<>();
        TransferMainBean transferMainBean = searchData(param);
        transferMainBean.setSapAccount(orderService.querySapAccount());
        transferMainBean.setUserName(tokenPrincipalProvider.getTokenPrincipal().getUsername());
        reMap = checkTransferDetail(transferMainBean);
        if(reMap.size() == 0){
            reMap = synTransferDetail(transferMainBean);
            if(StringUtils.isNotBlank(reMap.get(Constant.SAP_PROOF_NUM))){
                String sapCode = reMap.get(Constant.SAP_PROOF_NUM);
                this.updateSapCode(param.getIds(),sapCode);
            }
        }

        return  reMap;
    }

    /**
     * 修改总代系统成功后的U8凭证编码
     * @param resMaps
     */
    public void updateProxyCode(Map<String,Object> resMaps){
        Integer transferId = (Integer) resMaps.get("id");
        String  u8Code = (String) resMaps.get(Constant.U8_PROOF_NUM);
        TransferDetail beans = new TransferDetail();
        beans.setId(transferId);
        beans.setU8No(u8Code);
        if(null != transferId && StringUtils.isNotBlank(u8Code)){
            transferDetailMapper.updateByPrimaryKeySelective(beans);
        }
    }

    /**
     * 打款记录传输
     * @param beans
     * @return
     */
    public Map<String, String> synTransferDetail(TransferMainBean beans){
        Map<String, String>  resMap = new HashedMap();
        View view = restTemplate.postForEntity("http://dean-saprfc/saprfc/v1/saprfc/transfer/transmit/", beans,
                View.class).getBody();
        if(view.getCode()==20000 && view.getData() != null){
            resMap= (Map<String, String>) view.getData();
        }

        return resMap;
    }
}
